using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;

namespace ACM.cmsarea08.Controls
{
    public class FileUploadHandler: System.Web.IHttpHandler
    {
        const string imgForm = ".jpg,.jpeg,.gif,.png";
        public bool IsReusable { get { return true; } }
        public void ProcessRequest(System.Web.HttpContext contesto)
        {
            string chiave = "";
            string ope = "";
            string fileName = "";
            byte[] filedati;
            //string FileStreamData = "";
            if (HttpContext.Current.Request.Params["k"] == null) return;
            if (HttpContext.Current.Request.Params["ope"] == null) { nulla("no ope"); return; }
            //if (HttpContext.Current.Request.Params["dt"] == null) { nulla("no dt"); return; }

            chiave = HttpContext.Current.Request.Params["k"].ToString();
            ope = HttpContext.Current.Request.Params["ope"].ToString();
            //FileStreamData = HttpUtility.UrlDecode(HttpContext.Current.Request.Params["dt"].ToString());
            //if (HttpContext.Current.Cache.Get("DATIIMG" + chiave) == null) { nulla("no dati A"); return; }
            //if (HttpContext.Current.Cache.Get("NAMEIMG" + chiave ) == null) { nulla("no filename A"); return; }

            //filedati = (byte[])HttpContext.Current.Cache.Get("DATIIMG" + chiave);
            //fileName = (string)HttpContext.Current.Cache.Get("NAMEIMG" + chiave);
            ACM.cmsarea08.Function.CacheFileObjectInfo cInfo = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObjectInfo(HttpContext.Current,
                chiave);
            if (!cInfo.exists || cInfo.filename.Trim().Length == 0)
            {
                nulla("no filename"); return;
            }
            fileName = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObject(HttpContext.Current, chiave);
            if (fileName.IndexOf('#') == -1)
            {
                nulla("no filedata - cut "); return;
            }
            filedati = Convert.FromBase64String(fileName.Substring(fileName.IndexOf('#') + 1));
            fileName = fileName.Substring(0, fileName.IndexOf('#'));

            if (fileName.Trim() == "") { nulla("no filename"); return; }
            if (filedati == null) { nulla("no filedata"); return; }

//            filedati = ACM.cmsarea08.formdataadapter.Adapter.Decompress(filedati);

            if (ope.ToLower() == "p")
            {
                if (fileName.Trim().IndexOf('.') == -1) { nulla("no ext"); return; }
                string ext = fileName.Trim().Substring(fileName.Trim().LastIndexOf('.'));
                if(imgForm.IndexOf(ext.ToLower())==-1) {
                    //load ICONA.
                    LoadIcona(ext);
                } else {
                    //loadIMAGE.
                    LoadIMAGE(filedati, ext.ToLower());
                }
                //if filename endswith image.:
            }
            else
            {
                //processo di download.
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                HttpContext.Current.Response.AddHeader("Content-Length", filedati.Length.ToString());
                MemoryStream mr = new MemoryStream(filedati);
                mr.WriteTo(HttpContext.Current.Response.OutputStream);
                //HttpContext.Current.Response.OutputStream = filedati;
                HttpContext.Current.Response.End();
                mr.Close();
                mr.Dispose();
            }

        }

        private void LoadIcona(string ext)
        {
            //
            Bitmap bmp = null;
            
            switch (ext.ToLower())
            {
                case ".mov": case ".avi" : case ".dvx" : 
                case ".divx": case ".mpg" : case ".mpeg" :
                case ".3gp":  case ".asf": case ".mp4":
                    bmp = Risorse.ControlsResource.video; break;

                case ".wav" : case ".mp3" : case ".midi" : case ".aiff":
                    bmp = Risorse.ControlsResource.sound; break;
                default:
                    bmp = Risorse.ControlsResource.document; break;
            }

            if (bmp == null) { nulla("no icon"); return; }
            System.Drawing.Image low = bmp.GetThumbnailImage(35, 35, null, IntPtr.Zero);
            HttpContext.Current.Response.ContentType = "image/jpeg";
            low.Save(HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            HttpContext.Current.Response.End();

        }


        private void LoadIMAGE(byte[] data,string extension)
        {
            try
            {
                if (data.Length == 0)
                {
                    nulla("no dati byte[]");
                    return;
                }
                System.IO.MemoryStream mr = new System.IO.MemoryStream(data);
                System.Drawing.Image im = System.Drawing.Image.FromStream(mr,true);
                if (im == null) return;
                System.Drawing.Image low = im.GetThumbnailImage(35, 35, null, IntPtr.Zero);
                //HttpContext.Current.Response.ContentType = "image/jpeg";
                switch (extension)
                {
                    case ".gif":
                        HttpContext.Current.Response.ContentType = "image/gif";
                        break;
                    case ".jpg":
                        HttpContext.Current.Response.ContentType = "image/jpeg";
                        break;
                    case ".jpeg":
                        HttpContext.Current.Response.ContentType = "image/jpeg";
                        break;
                    case ".png":
                        HttpContext.Current.Response.ContentType = "image/png";
                        break;
                    default:
                        throw new NotSupportedException("Unrecognized image type.");
                } 
                low.Save(HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                HttpContext.Current.Response.End();
                low.Dispose();
                im.Dispose();
                mr.Close();
            }
            catch (Exception ex)
            {
                //non renderizzo nulla.
                nulla(ex.ToString());
                
            }
        }
        private void nulla(string message)
        {
            HttpContext.Current.Response.ContentType = "text/html";
            HttpContext.Current.Response.Write(message);
            HttpContext.Current.Response.End();
        }
    }
}
